<template>
  <div class="container-goods-search">

    <el-card class="container-goods-card">
      <template #header>
        <div class="card-header">
          <span>请输入商品内容</span>
        </div>
      </template>
      <el-row>
        <el-col :span="5" >
          <el-card class="category-card">
            <template #header>
              <div class="card-header">
                <span >请选择商品分类 <span style="color:red ;">(必选)</span></span>
              </div>
            </template>

            <el-cascader-panel
                v-model = 'selectOptions'
                placeholder="请选择商品分类"
                :options="categories"
                filterable
                clearable
                :show-all-levels="false"
            />
          </el-card>
        </el-col>
        <el-col :span="18" :offset="1" class="row-content">

          <el-row >
            <el-col :span="4">
              <span>请输入型号</span>
            </el-col>
            <el-col :span="5">
              <el-cascader class="search-input" placeholder="请输入型号" clearable
                           :options="type_names" filterable @change="typeChangeName"/>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-input placeholder="请输入或选择型号" v-model="goods.type_name" clearable/>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4">
              <span>请输入颜色</span>
            </el-col>
            <el-col :span="5">
              <el-cascader class="search-input" clearable
                           placeholder="输入颜色"
                           :options="colors"
                           filterable @change="typeChangeColor"/>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-input placeholder="请输入或选择颜色" v-model="goods.color" clearable/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <span>请输入商品名称</span>
            </el-col>
            <el-col :span="5">
              <el-cascader class="search-input" clearable
                           placeholder="输入名称"
                           :options="names"
                           filterable @change="changeName"/>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-input placeholder="请输入或选择商品名称" v-model="goods.name" clearable/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <span>请输入商品价格</span>
            </el-col>
            <el-col :span="16">
              <el-input placeholder="请输入商品价格" v-model="goods.price" clearable/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <span>请输入商品数量</span>
            </el-col>
            <el-col :span="16">
              <el-input placeholder="请输入商品数量" v-model="goods.count" @blur="mutable" clearable/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <span>请输入运费</span>
            </el-col>
            <el-col :span="16">
              <el-input placeholder="请输入运费" v-model="goods.transport" clearable @blur="mutable"/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <span>商品金额</span>
            </el-col>
            <el-col :span="16">
              <el-input v-model="goods.money" placeholder="自动计算,无须填写" disabled/>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="10" :offset="5" class="container-goods-button-box">
              <el-button class="container-goods-button" @click="goodsAdd" :disabled="isCreate">添加</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

  </div>
</template>

<script setup>

import {inject, onMounted, provide, ref, watch} from "vue";
import {invoke} from "@tauri-apps/api";
import {createId, showMessage} from '@/util/index'
import * as math from 'mathjs'

// 2.1 声明类型名称集合
let type_names = ref([])
// 3.1 声明颜色集合
let colors = ref([])
// 4.1 声明名称集合
let names = ref([])

// 2. 获取商品集合
let commodities = inject('commodities');
// 2.1 声明商品
let goods = ref({ id: '', category_id: '', type_name: '', color: '', name: '', price: '', count: '', transport: '', money: '' })
// 2.2 从组件获取所有商品的方法
const get_goods_all = inject("get_goods_all")
// 2. 调用商品管理页面的刷新
// 2. 向父组件暴露的方法发送请求 goodsFlush
// 2.3 在添加完数据后, 通过 emits 暴露的方法, 通知父组件刷新数据
const emits = defineEmits(["goodsFlush"]);
const get_goods_result_all = inject('get_goods_result_all');
// 1. 从挂载的组件中获取到商品分类集合
let categories = inject("categories") ;
// 1.2 声明选择商品分类的默认值
let selectOptions = ref([]);


/**
 * 6.1 过滤商品集合
 * @param goodses
 */
const filterArray = (goodses)=>{
  let colorMap = new Map();
  goodses.forEach(gg => { colorMap.set(gg.color, gg.color) })
  colors.value = []
  colorMap.forEach((k, v) => { colors.value.push({'label': k, 'value': v}) })
  let nameMap = new Map();
  goodses.forEach(gg => { nameMap.set(gg.name, gg.name) })
  names.value = []
  nameMap.forEach((k, v) => { names.value.push({'label': k, 'value': v}) })
}

/**
 * 5.1 名称选择
 */
const changeName = e => {
  if (e) {
    let name = e[0];
    let g = commodities.value.filter(g => {
      return name == g.name
    })
    goods.value.name = g[0].name;
  } else {
    goods.value.name = "";
  }
}

/**
 * 4.2 颜色选择
 * @param e
 */
const typeChangeColor = (e) => {
  if (e) {
    let color = e[0];
    let g = [];
    if(goods.value.type_name!=""){
      g = commodities.value.filter(g => {
        return category_id.value == g.category_id && g.color == color && g.type_name == goods.value.type_name
      })
    }else{
      g = commodities.value.filter(g => {
        return category_id.value == g.category_id && g.color == color
      })
    }
    goods.value.color = color;
    let nameMap = new Map();
    g.forEach(gg => {
      nameMap.set(gg.name, gg.name)
    })
    names.value = []
    nameMap.forEach((k, v) => {
      names.value.push({'label': k, 'value': v})
    })
  } else {
    goods.value.color = "";
    let g = [];
    if(goods.value.type_name!=""){
      g = commodities.value.filter(g => {
        return category_id.value == g.category_id && g.type_name == goods.value.type_name
      })
    }else{
      g = commodities.value.filter(g => {
        return category_id.value == g.category_id
      })
    }
    filterArray(g)
  }
  goods.value.category_id = category_id.value ;
}

/**
 * 3.2 型号选择时, 获取该型号下的所有颜色
 */
const typeChangeName = (e) => {
  if (e) {
    let typeName = e[0];
    let g = commodities.value.filter(g => {
      return category_id.value == g.category_id && typeName == g.type_name
    })

    goods.value.type_name = g[0].type_name;
    filterArray(g);
  } else {
    let g = commodities.value.filter(g => {
      return category_id.value == g.category_id
    })
    filterArray(g);
  }
  goods.value.category_id = category_id.value ;
}

let category_id = ref('');

// 2.4.2 在选择分类后, 获取当前分类的所有的型号 type_names 赋值
watch(selectOptions, (newValue) => {
  let value = '' ;
  if (typeof newValue === 'string'){
    value = newValue
  }else{
    value = newValue[0]
  }

  category_id.value = value ;
  goods.value.category_id = value ;
  invoke("choose_update",{choose:{id:"1",category_id:value}}).then(res=>{})
  // 给 goods 商品的 category_id 赋值

  // console.log(goods.value.category_id);
  if (value != '') {
    // 获取当前分类下的所有型号
    let filterGoods = commodities.value.filter(com=>{ return com.category_id == value })
    type_names.value = [];
    let type_nams_set = new Map();
    filterGoods.forEach( g => {type_nams_set.set(g.type_name, g.type_name);});
    type_nams_set.forEach((k, v) => { type_names.value.push({'label': k, 'value': v}) });
    filterArray(filterGoods)
  }
})



// 2.2.1 声明获取商品集合的方法
const get_all_goods = async ()=>{
  let res = await get_goods_all();
  if (res != undefined) {
    commodities.value = []
    JSON.parse(res).forEach((g) => {
      commodities.value.push(g)
    })
  }
  if(category_id.value === '1' && commodities.value.length > 0){
    category_id.value = commodities.value[0].category_id ;
    selectOptions.value = category_id.value ;
  }else{
    selectOptions.value = category_id.value ;
  }
  let filterGoods = commodities.value.filter(com=>{ return com.category_id == category_id.value })
  type_names.value = [];
  colors.value = [];
  names.value = [];
  let type_nams_set = new Map();
  filterGoods.forEach( g => {type_nams_set.set(g.type_name, g.type_name);});
  type_nams_set.forEach((k, v) => { type_names.value.push({'label': k, 'value': v}) });
  filterArray(filterGoods)
}




// 是否能创建商品 (应用在点击创建时, 未创建结束中, 防止用户再次点击)
let isCreate = ref(false);


/**
 * 7. 监听输入框的值, 改变商品金额
 */
const mutable = () => {
  if (goods.value.price != "" && goods.value.count != "") {
    goods.value.price = math.round(goods.value.price ,2);
    goods.value.count = math.round(goods.value.count, 2);
    goods.value.money = math.round(goods.value.price * goods.value.count,2);
    if (goods.value.transport != "") {
      goods.value.transport = math.round(goods.value.transport, 2)
      goods.value.money = math.round(goods.value.money + goods.value.transport,2);
    }
  }
}

/**
 * 商品添加方法
 */
const goodsAdd = () => {
  isCreate.value = true;
  goods.value.id = createId();
  goods.value.category_id = category_id.value ;
  goods.value.price = math.round(goods.value.price * 100 ,2) ;
  goods.value.count = math.round(goods.value.count, 2);
  goods.value.transport = math.round(goods.value.transport * 100, 2)  ;
  if (goods.value.transport == 0) {
    goods.value.money = math.round(goods.value.price * goods.value.count , 2 );
  } else {
    goods.value.money = math.round(goods.value.price * goods.value.count + goods.value.transport , 2) ;
  }
  // console.log(goods.value);
  goods.value.type_name = goods.value.type_name.trim();
  invoke("goods_insert", {"goods": goods.value}).then(res => {
    showMessage(res);
    goods.value = { id: '', category_id: category_id.value, type_name: '', color: '', name: '', price: '',  count: '',  transport: '', money: '' };
    isCreate.value = false;
    // 需要查询所有的商品
    get_all_goods();
    emits('goodsFlush')
    get_goods_result_all();
  })
}


const get_choose_category_id = ()=>{
  invoke("choose_search").then(res=>{
    category_id.value = res ;
    goods.value.category_id = category_id.value ;
  })
}
onMounted(() => {
  get_choose_category_id();
  get_all_goods();

})
</script>

<style scoped lang="scss">
.container-goods-search {
  position: absolute;
  width: 100%;
  .container-goods-card{
    width: 88vw;
    .category-card{

      ::v-deep(.el-card__body){
        padding: 10px ;
        overflow: scroll;
        height: 530px;
        .el-cascader-panel{
          //width: 400px;
          margin: 0 ;

          //width: 400px;
          .el-cascader-menu{
            width: 100%;

            max-height: 530px;
            .el-cascader-menu__wrap{
              width: 100%;
              height: 525px;
              .el-scrollbar__view{

                .el-cascader-node{

                  width: 80%;
                  margin: 0 auto ;
                  //font-size: 14px;
                  line-height: 30px;
                  height: 30px;
                  //width: 160px;
                  text-align: center;
                  .el-cascader-node__label{
                    margin: 0 auto ;

                  }
                }
              }
            }
          }
        }


      }
    }


    .row-content{
      .el-row{
        margin: 30px 0 0 0 ;
      }
      .el-row:nth-child(1){
        margin: 80px 0 0 0 ;
      }

    }
  }

}
:deep(.el-card__body){
  height: 615px;
}

.container-goods-input {
  display: flex;
  justify-content: flex-start;

  span {
    display: block;
    width: 300px;
  }
}

.container-goods-button-box {

  display: flex;
  justify-content: center;
  align-items: center;
}

.container-goods-button {
  width: 180px;
  height: 50px;
  margin: 20px 0 0 0;
}

</style>